import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;

//http://client-serveur-2013.googlecode.com/svn/trunk/SocketUtils/src/

public class SocketClient {

	protected long timeoutDebug = 5000;
	private static final boolean DEBUG = false;


	protected void trace(String mesg) {
		System.out.println("(" + mesg + ")");
	}

	protected void slog(String mesg) {
		System.out.println(" response: " + mesg);
	}

	protected void rlog(String mesg) {
		System.out.println(" request: " + mesg);
	}

	public String randomString(int len) {
		char[] str = new char[len];
		for (int i = 0; i < len; i++)
			str[i] = (char) (((int) (Math.random() * 26)) + (int) 'A');
		return (new String(str).toLowerCase());
	}

	public String randomText(int len) {
		String result = "";
		for (int i = 0; i < len; i++)
			result += randomString((int) (Math.random() * 10)) + " ";
		return result;
	}


	private  String readResponseDebug(DataInputStream in) throws IOException {
		String response = null;
		final long start = System.currentTimeMillis();
		while (response == null) {
			int received = in.available();
			if (received > 0) {
				byte[] b = new byte[received];
				in.readFully(b);
				response = new String(b);
			}
			if (System.currentTimeMillis() - start > timeoutDebug) {
			  trace("no response");
			  return "";
			}
		}
		String[] resp = response.split("\r\n");
		if (resp.length > 1)
			System.out.println("[");
		for (String r : resp)
			slog(r);
		if (resp.length > 1)
			System.out.println("]");
		return response;
	}

	@SuppressWarnings("deprecation")
	protected String readResponse(DataInputStream in)
			throws IOException {
		if (DEBUG){
			return readResponseDebug(in);
		} else{
		String response=in.readLine();
		String[] resp = response.split("\r\n");
		if (resp.length > 1)
			System.out.println("[");
		for (String r : resp)
			slog(r);
		if (resp.length > 1)
			System.out.println("]");
		return response;
		}
	}

	protected void sendRequest(PrintStream writer, String request) {
		rlog(request);
		writer.println(request);
	}

	public static void main(String[] args) {
		SocketClient test = new SocketClient();
		test.trace("tests Base64");
		String username = "cs2013";
		String password = "emacs2013";
		test.trace(username + " -> "
				+ Base64.encodeToString(username.getBytes(), false));
		test.trace(password + " -> "
				+ Base64.encodeToString(password.getBytes(), false));

		test.trace(new String(Base64.decode("VXNlcm5hbWU6")) + " <- "
				+ "VXNlcm5hbWU6");

	}

}
